package com.dimld.connect.http;

import com.dimld.connect.MsgReaderI;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionException;

public class RequestPool implements HttpHandler {
    private final Logger   httpLog = LoggerFactory.getLogger("http");
    private final Class<?> httpReaderClass;
    private final int      timeout;
    private final String   serviceUUID;

    public RequestPool(Class<?> httpReaderClass, int timeout, String serviceUUID) {
        this.httpReaderClass = httpReaderClass;
        this.timeout = timeout;
        this.serviceUUID = serviceUUID;
    }

    @Override
    public void handleRequest(HttpServerExchange httpServerExchange){
        String hostAndPort = httpServerExchange.getHostAndPort();
        String requestURI = httpServerExchange.getRequestURI();
        httpLog.info("[HTTP]收到请求：" + hostAndPort + " " + requestURI);
        try {
            MsgReaderI mr = (MsgReaderI) httpReaderClass.newInstance();
            httpServerExchange.getRequestReceiver().receiveFullBytes(new HttpHandle(httpServerExchange, mr, timeout, serviceUUID));
        } catch (InstantiationException e) {
            httpLog.error("指定的类对象无法被实例化", e);
        } catch (IllegalAccessException e) {
            httpLog.error("正在执行的方法无法访问指定类、字段、方法或构造方法的定义");
        } catch (RejectedExecutionException e) {
            httpLog.error("无法执行该线程", e);
        } catch (NullPointerException e) {
            httpLog.error("执行的对象为null", e);
        }
    }

}
